<template>
  <el-dialog
    :title="!form.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    width="500px"
    :visible.sync="visible">
    <el-form size="mini" :model="form" :rules="rules" ref="form" @keyup.enter.native="submitForm()" label-width="80px">
      <el-form-item label="需求名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入需求名称"></el-input>
      </el-form-item>
      <el-form-item label="联系人" prop="linkman">
        <el-input v-model="form.linkman" placeholder="请输入联系人"></el-input>
      </el-form-item>
      <el-form-item label="联系方式" prop="linkman">
        <el-input v-model="form.phone" placeholder="请输入联系方式"></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="form.status" placeholder="请选择状态">
          <el-option
            v-for="dict in dict.type.purchase_status"
            :key="dict.value"
            :label="dict.label"
            :value="parseInt(dict.value)"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button size="mini" icon="el-icon-circle-check" type="primary" @click="submitForm()">确定</el-button>
      <el-button size="mini" icon="el-icon-circle-close" @click="visible = false">取消</el-button>
    </span>
  </el-dialog>
</template>

<script>
import {getPurchase, savePurchase, updatePurchase} from '@/api/ware/purchase'

export default {
  dicts: ['purchase_status'],
  data() {
    return {
      visible: false,
      form: {},
      rules: {
        name: [
          {required: true, message: '请输入需求名称', trigger: 'blur'}
        ],
        linkman: [
          {required: true, message: '请输入联系人', trigger: 'blur'}
        ],
        phone: [
          {required: true, message: '请输入手机号', trigger: 'blur'}
        ],
        status: [
          {required: true, message: '请选择状态', trigger: 'blur'}
        ]
      }
    }
  },
  methods: {
    edit(id) {
      this.visible = true
      this.$nextTick(() => {
        this.$refs['form'].resetFields()
        getPurchase(id).then(res => {
          if (res.success) {
            this.form = res.data
          }
        })
      })
    },
    add() {
      this.form = {
        status: 0
      }
      this.visible = true
    },
    // 表单提交
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (!this.form.id) {
            savePurchase(this.form).then(res => {
              if (res.success) {
                this.$message.success('需求新增成功')
                this.visible = false
                this.$emit('ok')
              }
            })
          } else {
            updatePurchase(this.form).then(res => {
              if (res.success) {
                this.$message.success('需求修改成功')
                this.visible = false
                this.$emit('ok')
              }
            })
          }
        }
      })
    }
  }
}
</script>
